package cn.xxliang.platapp.common;

import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

@Slf4j
public class SkyErrMsgUtil {

    private Map<Integer, String> errMsgMap;

    private static final String fileName = "code_msg";

    static class ErrMsgUtilsHolder {
        public static SkyErrMsgUtil utils = new SkyErrMsgUtil();
    }

    public SkyErrMsgUtil() {
        this.errMsgMap = new HashMap<>();

        Properties property = getProperty();
        if (property == null) {
            log.error("ErrMsgUtils.initializer.error,fileName=" + fileName);
            return;
        }

        Enumeration<Object> keys = property.keys();
        while (keys.hasMoreElements()) {
            String strKey = String.valueOf(keys.nextElement());
            Integer key = Integer.parseInt(strKey);
            String value = property.getProperty(strKey, "");
            try {
                value = new String(value.getBytes("ISO-8859-1"), "UTF8");
                this.errMsgMap.put(key, value);
            } catch (UnsupportedEncodingException e) {
                log.error(e.getMessage(), e);
            }
        }
        log.info("ErrMsgUtils.initializer.finish,size=" + this.errMsgMap.size());
    }

    private Properties getProperty() {
        Properties properties = new Properties();
        InputStream in = this.getClass().getClassLoader().getResourceAsStream(fileName + ".properties");
        if (in == null) {
            log.info("ErrMsgUtils.getProperty.can't find,fileName=" + fileName + ".properties");
            return null;
        }
        try {
            properties.load(in);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return properties;
    }

    public static SkyErrMsgUtil ins() {
        return ErrMsgUtilsHolder.utils;
    }

    public String getMsg(Integer key) {
        String value = errMsgMap.get(key);
        return value == null ? "" : value;
    }
}
